//
// /etc/influxdb/influxdb.conf
//
//[subscriber]
//enabled = true
//http-timeout = "5s"
//insecure-skip-verify = false
//ca-certs = ""
//write-concurrency = 1
//write-buffer-size = 1024

// influx -username admin -password xBjphjlkZTHC1Ks4UVDd -database zdcp
// show SUBSCRIPTIONs
// CREATE SUBSCRIPTION "mysub" ON "zdcp"."autogen" DESTINATIONS ALL 'udp://10.10.236.52:9088'
// CREATE SUBSCRIPTION "mysub2" ON "zdcp"."autogen" DESTINATIONS ALL 'http://10.10.236.52:9099/api/alarm-flow/influxdb-subscriber'
// DROP SUBSCRIPTION "mysub2" ON "zdcp"."autogen"

package main

import (
	"alarm-flow/config"
	"alarm-flow/datasource"
	"alarm-flow/handler"
	"alarm-flow/handler/pipeline"
	"alarm-flow/utils"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/pprof"
	"os"
)

var err error
var globalConfig *config.Config

func init() {
	globalConfig, err = config.New("")
	if err != nil {
		panic(err)
	}

	err = datasource.InitPg(globalConfig.Pg)
	if err != nil {
		panic(err)
	}

	err = datasource.InitRedis(globalConfig.Redis)
	if err != nil {
		panic(err)
	}

	log := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		//AddSource:   true,
		Level: utils.SlogLevel(globalConfig.LogLevel),
	}))
	slog.SetDefault(log)

	// 业务缓存数据预热
	err = pipeline.SyncAlarmConfig()
	if err != nil {
		panic(err)
	}

	err = pipeline.SyncInstState()
	if err != nil {
		panic(err)
	}
}

func main() {
	app := http.NewServeMux()
	app.HandleFunc("/debug/pprof/", pprof.Index)
	app.HandleFunc("/debug/sub/", handler.Debug)
	app.HandleFunc("/api/alarm-flow/influxdb-subscriber/write", handler.Subscriber)

	slog.Info("Service start")

	err = http.ListenAndServe(fmt.Sprintf(":%d", globalConfig.ListenPort), app)
	if err != nil {
		slog.Error("ListenAndServe: ", "error", err)
		os.Exit(-1)
	}
}
